package com.example.springboot.config.filter;

import com.example.springboot.service.IUserService;
import com.example.springboot.service.impl.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;

@Configuration
@RequiredArgsConstructor
public class FilterConfig {

    private static final long MAX_AGE = 24 * 60 * 60; // 当前跨域请求最大有效时长。这里默认1天

    private final IUserService userService;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 允许所有来源
        corsConfiguration.addAllowedHeader("*"); // 允许所有请求头
        corsConfiguration.addAllowedMethod("*"); // 允许所有方法
        corsConfiguration.setMaxAge(MAX_AGE); // 设置有效时长
        source.registerCorsConfiguration("/**", corsConfiguration); // 对所有接口配置跨域设置
        return new CorsFilter(source);
    }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
        FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(corsFilter());
        registration.setOrder(1);  // 跨域过滤器优先执行
        return registration;
    }

    @Bean
    public FilterRegistrationBean<JwtFilter> jwtFilterRegistration() {
        FilterRegistrationBean<JwtFilter> registration = new FilterRegistrationBean<>();
        JwtFilter jwtFilter = new JwtFilter(userService);
        registration.setFilter(jwtFilter);
        registration.addUrlPatterns("/*"); // 设置过滤器的URL模式
        registration.setName("jwtFilter");
        registration.setOrder(2); // 确保跨域过滤器先执行
        return registration;
    }
}
